﻿#include "areatest.h"

AreaTest::AreaTest(QWindow *parent) : QOpenGLWindow(QOpenGLWindow::NoPartialUpdate, parent),
    pContext(nullptr), pShader(nullptr), pServer(nullptr)
{
    this->setSurfaceType(QWindow::OpenGLSurface);
    pServer = GLServer::getInstance();
    this->create();
}

AreaTest::~AreaTest()
{
    delete pContext;
    pContext = nullptr;
    pServer->destroy();
}

void AreaTest::initializeGL()
{
    initializeOpenGLFunctions();
    qDebug() << this->context();
    pContext = new QOpenGLContext;   
    qDebug() << pContext->create() << "ini_1";
    qDebug() << pContext;
    qDebug() << pContext->makeCurrent(this) << "ini_2";
    initializeOpenGLFunctions();
    pShader = new QOpenGLShaderProgram(this);
    qDebug() << pShader->addShaderFromSourceFile(QOpenGLShader::Vertex, ":/Shader/Shader/normalV.vsh") << "ini_3";
    qDebug() << pShader->addShaderFromSourceFile(QOpenGLShader::Fragment, ":/Shader/Shader/fragShader.fsh") << "ini_4";
    qDebug() << pShader->link() << "ini_5";
    posAttr = pShader->attributeLocation("pos");
    colorUni = pShader->uniformLocation("currentColor");
    pContext->doneCurrent();
}

void AreaTest::resizeGL(int w, int h)
{
    qDebug() << pContext->makeCurrent(this) << "re_1";
    qDebug() << QOpenGLContext::currentContext();
    if (QOpenGLContext::currentContext()) {
        QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();
        f->glViewport(0, 0, w, h);
    }
    pContext->doneCurrent();
}

void AreaTest::paintGL()
{
    qDebug() << pContext->makeCurrent(this) << "pt_1";
    qDebug() << QOpenGLContext::currentContext();
    QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();
    f->glClearColor(0.0, 0.0, 0.0, 1.0);
    f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    qDebug() << pShader->bind() << "pt_2";
    pShader->setAttributeArray(posAttr, pServer->getBackVertexData(), 2, 0);
    pShader->setUniformValue(colorUni, pServer->getColor(GLServer::ColorVector::LINE_COLOR));
    pShader->enableAttributeArray(posAttr);
    f->glDrawArrays(GL_POINTS, 0, pServer->getBackVertexSize());
    pShader->disableAttributeArray(posAttr);
    pContext->swapBuffers(this);
    pShader->release();
    this->update();
//    pContext->doneCurrent();
}
